const { query } = require('../../helper/db');
const { ok, door } = require('../../helper/util');

module.exports = async ctx => {
  var token = ctx.headers.authorization;
  var params = ctx.query;
  var user = await door(token);
  var page = params.page || 1;
  var size = params.size || 10;
  var end = page * size;
  var sql = ['select * from chat_records where 1 = 1'];
  var values = [];

  sql.push('and touserid = ?');
  values.push(user.id);

  if (params.fromuserid) {
    sql.push('and userid = ?');
    values.push(params.fromuserid);
  }

  if (params.status) {
    sql.push('and status = ?');
    values.push(params.status);
  }

  sql.push('order by id desc limit ?, ?');
  values.push(end - size, end);

  var records = await query(sql.join(' '), values);

  ctx.body = ok({ records });
};
